package lion.framework.core.web.exception;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import lion.framework.core.util.StringLengthCompartor;

import org.apache.commons.lang.StringUtils;

public class WEBExceptionHandlers {

	private static Map<String, IExceptionHandler> pathHandlers = new HashMap<>();
	private static Map<String, IExceptionHandler> paternHandlers = new TreeMap<>(new StringLengthCompartor());

	public static final IExceptionHandler DEFAULT_HANDLER = new DefaultExceptionHandler();

	public static void addHandler(String path, IExceptionHandler handler) {

		if (StringUtils.isBlank(path)) { return; }

		if (path.indexOf("*") > -1 || path.indexOf("$") > -1 || path.indexOf("^") > -1) {
			paternHandlers.put(path, handler);
		} else {
			pathHandlers.put(path, handler);
		}
	}

	public static IExceptionHandler getExceptionHandler(String path) {

		IExceptionHandler handler = pathHandlers.get(path);
		if (handler == null) {

			for (String pattern : paternHandlers.keySet()) {
				if (path.matches(pattern)) {
					handler = paternHandlers.get(pattern);
					break;
				}
			}
		}
		if (handler == null) {
			handler = DEFAULT_HANDLER;
		}
		return handler;
	}
}